import {
  pgTable,
  serial,
  text,
  numeric,
  index,
  timestamp,
  date
} from 'drizzle-orm/pg-core'
import { z } from 'zod'

import { createInsertSchema, createSelectSchema } from 'drizzle-zod'
import { sql } from 'drizzle-orm'

export const expenses = pgTable(
  'expenses',
  {
    id: serial('id').primaryKey(),
    title: text('title').notNull(),
    amount: numeric('amount', { precision: 12, scale: 2 }).notNull(),
    date: date('date').notNull(),
    userId: text('user_id').notNull(),
    createdAt: timestamp('create_at')
      .notNull()
      .default(sql`(now() + interval '8 hours')`)
  },
  expenses => ({
    userIdIdx: index('user_id_idx').on(expenses.userId)
  })
)

export const expenseSelectSchema = createSelectSchema(expenses, {
  title: z.string().min(3, { message: 'Title must be at least 3 characters' }),
  amount: z.string().regex(/^\d+(\.\d{1,2})?$/, {
    message: 'Amount must be a number with up to 2 decimal places'
  })
})
export const expenseInsertSchema = createInsertSchema(expenses)
